package com.copm.ifm.servers.sys.dataauth;

import cn.hutool.core.collection.CollectionUtil;
import com.copm.ifm.base.basic.getter.StaticDataGetter;
import com.copm.ifm.base.basic.util.AuthUtils;
import com.copm.ifm.base.service.mp.dataauth.component.AbstractDataAuthSqlHandler;
import com.copm.ifm.servers.sys.entity.SysRole;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.ValueListExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色数据权限限制sql处理器
 *
 * @author zzf
 * @date 2021/2/19 15:58
 */
public class MyRoleDataAuthSqlHandler extends AbstractDataAuthSqlHandler<List<String>, InExpression> {

    public MyRoleDataAuthSqlHandler() {

        super(SysRole.class,
                "sr",
                new StaticDataGetter<>(AuthUtils::getCurrentUserRole),
                SysRole::getTenantId,
                SysRole::getId);
    }

    @Override
    protected InExpression setOperatorValue(List<String> data) {
        InExpression operator = new InExpression();
        Column whereColumn = new Column(super.whereColumnName);
        whereColumn.setTable(getLimitTable());
        operator.setLeftExpression(whereColumn);

        ValueListExpression listExpression = new ValueListExpression();
        List<Expression> expressions = new ArrayList<>();
        data.forEach(s -> {
            StringValue stringValue = new StringValue(s);
            expressions.add(stringValue);
        });

        listExpression.setExpressionList(new ExpressionList(expressions));

        operator.setRightExpression(listExpression);
        return operator;
    }

    @Override
    protected boolean parseIfDataAbsent() {
        return false;
    }

    @Override
    protected boolean dataIsFull(List<String> data) {
        if (CollectionUtil.isNotEmpty(data)) {
            return data.size() > 2;
        }
        return false;
    }

    /**
     * 判断该数据是否属于全部权限数据
     *
     * @param data 数据权限数据
     */
    @Override
    protected boolean dataIsNull(List<String> data) {
        return CollectionUtil.isEmpty(data);
    }

    @Override
    public int getId() {
        return SqlHandlerIdEnum.ROLE.getId();
    }

}
